<?php

namespace Api\Jobs;

use Api\Http\Controllers\WechatController;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Modules\Express\Models\ExpressPlatform;
use Modules\Member\Models\Members;
use Modules\Member\Models\MembersPriceLog;
use Modules\Member\Models\MembersProfit;
use Modules\Order\Models\Orders;


class MemberProfitTask implements ShouldQueue
{
    use Queueable, Dispatchable, InteractsWithQueue, SerializesModels;

    public array $data;

    /**
     * Create a new job instance.
     */
    public function __construct($data)
    {
        $this->data = $data;
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {

        $orderId = $this->data['orderId'];
        $userId = $this->data['userId'];
        $useCoupon = $this->data['useCoupon'];
        $first = $this->data['first'] ?? '';
        $more = $this->data['more'] ?? '';
        $platform = $this->data['platform'] ?? 3;
        $calWeight = $this->data['calWeight'] ?? '';
        if ($first) {

            $this->firstProfit($orderId, $userId, $useCoupon);
        }
        if ($more) {
            $this->moreProfit($userId, $orderId, $platform, $calWeight, $useCoupon);
        }

    }

    private function firstProfit($orderId, $userId, $useCoupon)
    {
        $wechat = new WechatController();
        $templateId = "a5SwcAaVdMm6qHnMJJHNwzakOjoHKsPFkLcpneE57H4";
        $userInfo = Members::find($userId);
        $orderInfo = Orders::find($orderId);
        $v1Max = config('level')['v1_count'];
        $v2Max =   config('level')['v2_count'];
        $flag = $useCoupon;
        //市代返利
        $senderCity = $orderInfo->sender_city;
        $haveShi = strpos($senderCity, '市');
        $agent = Members::whereLike('agent_city_name', $senderCity . '%')->where('agent_end_at', '>', time())->first();
        if (!$agent && $haveShi) {
            $senderCity = substr($senderCity, 0, -3);
            $agent = Members::whereLike('agent_city_name', $senderCity . '%')->where('agent_end_at', '>', time())->first();
        }
        if ($agent) {
            $priceLog = new MembersPriceLog();
            $priceLog->user_id = $agent->id;
            $priceLog->start_user_id = $orderInfo->user_id;
            $priceLog->money = 0.1;
            $priceLog->type = 2;
            $priceLog->status = 0;
            $priceLog->order_sn = $orderInfo->order_sn;
            $priceLog->waybill = $orderInfo->waybill;
            $priceLog->save();
            $profit = [];
            $profit['user_id'] = $agent->id;
            $profit['type'] = 3; //市代返利
            $profit['order_id'] = $orderId;
            $profit['profit'] = 0.1;
            MembersProfit::create($profit);
        }
        //上级
        $path = Redis::hget($userId, 'path');
        if (!empty($path)) {
            $pathArr = explode(",", $path);
            $pathArr2 = array_reverse($pathArr);
            $v1Count = 0;
            $v2Count = 0;
            foreach ($pathArr2 as $id) {
                $profit = [];
                $profit['user_id'] = $id;
                $profit['order_id'] = $orderId;
                $profit['type'] = 1; //续重分销
                $pinfo = Members::select(['pid', 'id', 'user_level', 'lose_all', 'gzh_open_id','user_count','v1_count'])->find($id);
                if (empty($pinfo)) continue;
                if ($userInfo->user_level == 0) {
                    //增加总流失金额  v0-v0
                    if ($pinfo->user_level == 0 && $id == $userInfo->pid) {
                        Members::where('id', $id)->increment('lose_all', 0.7);

                        if($pinfo->user_count == ($v1Max-1)){
                            Members::where('id', $id)->update(['user_level'=>1]);
                        }else{
                            Members::where('id', $id)->increment('user_count');
                        }

                    } //v1返利  v0-v1
                    elseif ($pinfo->user_level == 1 && $v1Count == 0 && $v2Count == 0) {
                        $v1Count = 1;
                        //使用优惠券
                        if ($flag == true) {
                            $profit['profit'] = 0.1;
                            MembersProfit::create($profit);
                        } else {
                            //不适用优惠券
                            $profit['profit'] = 0.7;
                            MembersProfit::create($profit);
                        }
                    } //v0-v2
                    elseif ($pinfo->user_level == 2 && $v1Count == 0 && $v2Count == 0) {
                        $v2Count = 1;
                        //使用优惠券
                        if ($flag == true) {
                            $profit['profit'] = 0.1;
                            MembersProfit::create($profit);

                        } else {
                            //不适用优惠券
                            $profit['profit'] = 0.7;
                            MembersProfit::create($profit);

                        }
                    } //v0-v1-v2
                    elseif ($pinfo->user_level == 2 && $v1Count == 1 && $v2Count == 0) {
                        $v2Count = 1;
                        //使用优惠券
                        if ($flag == false) {
                            $profit['profit'] = 0.24;
                            MembersProfit::create($profit);

                        }
                    } //v0-v2-v2
                    elseif ($pinfo->user_level == 2 && $v1Count == 0 && $v2Count == 1) {
                        $v2Count = 2;
                        //使用优惠券
                        if ($flag == false) {
                            $profit['profit'] = 0.35;
                            MembersProfit::create($profit);
                        }
                    } //v0-v1-v2-v2
                    elseif ($pinfo->user_level == 2 && $v1Count == 1 && $v2Count == 1) {
                        $v2Count = 2;
                        //使用优惠券
                        if ($flag == false) {
                            $profit['profit'] = 0.12;
                            MembersProfit::create($profit);

                        }
                    } elseif ($pinfo->user_level == 2 && $v2Count == 2) {
                        $v2Count = 3;
                        if ($flag == false) {
                            $profit['profit'] = 0.1;
                            MembersProfit::create($profit);

                        }
                    } elseif ($pinfo->user_level == 2 && $v2Count == 3) {
                        if ($flag == false) {
                            $v2Count = 4;
                            $profit['profit'] = 0.1;
                            MembersProfit::create($profit);
                        }
                    } elseif ($pinfo->user_level == 2 && $v2Count == 4) {
                        if ($flag == false) {
                            $profit['profit'] = 0.1;
                            MembersProfit::create($profit);
                            $priceLog = [];
                            $priceLog = new MembersPriceLog();
                            $priceLog->user_id = $id;
                            $priceLog->start_user_id = $orderInfo->user_id;
                            $priceLog->money = $profit['profit'];
                            $priceLog->type = 2;
                            $priceLog->status = 0;
                            $priceLog->order_sn = $orderInfo->order_sn;
                            $priceLog->waybill = $orderInfo->waybill;
                            $priceLog->save();
                            if (!empty($pinfo['gzh_open_id'])) {
                                $data = [
                                    'character_string12' => ['value' => $orderInfo->order_sn],
                                    'amount6' => ['value' => $orderInfo->money],
                                    'amount13' => ['value' => (string)$profit['profit']],
                                ];
                                $wechat = new WechatController();
                                $wechat->sendOfficialMessage($pinfo['gzh_open_id'], $templateId, $data);
                            }
                            break;
                        }
                    }

                } //v1
                elseif ($userInfo->user_level == 1) {
                    if($pinfo->user_level == 1){
                        if ($pinfo->v1_count == ($v2Max-1)){
                            Members::where('id', $id)->update(['user_level'=>2]);
                        }else{
                            Members::where('id', $id)->increment('v1_count');
                        }
                    }
                    //v1-v2
                    if ($pinfo->user_level == 2 && $v2Count == 0) {
                        $v2Count = 1;
                        $profit['profit'] = 0.24;
                        MembersProfit::create($profit);
                    } //v1-v2-v2
                    elseif ($pinfo->user_level == 2 && $v2Count == 1) {
                        $v2Count = 2;
                        $profit['profit'] = 0.12;
                        MembersProfit::create($profit);

                    } elseif ($pinfo->user_level == 2 && $v2Count == 2) {
                        $v2Count = 3;
                        $profit['profit'] = 0.1;
                        MembersProfit::create($profit);
                    } elseif ($pinfo->user_level == 2 && $v2Count == 3) {
                        $v2Count = 4;
                        $profit['profit'] = 0.1;
                        MembersProfit::create($profit);
                    } elseif ($pinfo->user_level == 2 && $v2Count == 4) {
                        $profit['profit'] = 0.1;
                        MembersProfit::create($profit);
                        $priceLog = [];
                        $priceLog = new MembersPriceLog();
                        $priceLog->user_id = $id;
                        $priceLog->start_user_id = $orderInfo->user_id;
                        $priceLog->money = $profit['profit'];
                        $priceLog->type = 2;
                        $priceLog->status = 0;
                        $priceLog->order_sn = $orderInfo->order_sn;
                        $priceLog->waybill = $orderInfo->waybill;
                        $priceLog->save();
                        if (!empty($pinfo['gzh_open_id'])) {
                            $data = [
                                'character_string12' => ['value' => $orderInfo->order_sn],
                                'amount6' => ['value' => $orderInfo->money],
                                'amount13' => ['value' => (string)$profit['profit']],
                            ];
                            $wechat = new WechatController();
                            $wechat->sendOfficialMessage($pinfo['gzh_open_id'], $templateId, $data);
                        }
                        break;
                    }

                } //v2
                elseif ($userInfo->user_level == 2) {
                    //v2-v2
                    if ($pinfo->user_level == 2 && $v2Count == 0) {
                        $v2Count = 1;
                        $profit['profit'] = 0.35;
                        MembersProfit::create($profit);
                    } elseif ($pinfo->user_level == 2 && $v2Count == 1) {
                        $v2Count = 2;
                        $profit['profit'] = 0.1;
                        MembersProfit::create($profit);
                    } elseif ($pinfo->user_level == 2 && $v2Count == 2) {
                        $v2Count = 3;
                        $profit['profit'] = 0.1;
                        MembersProfit::create($profit);
                    } elseif ($pinfo->user_level == 2 && $v2Count == 3) {
                        $profit['profit'] = 0.1;
                        MembersProfit::create($profit);
                        $priceLog = [];
                        $priceLog = new MembersPriceLog();
                        $priceLog->user_id = $id;
                        $priceLog->start_user_id = $orderInfo->user_id;
                        $priceLog->money = $profit['profit'];
                        $priceLog->type = 2;
                        $priceLog->status = 0;
                        $priceLog->order_sn = $orderInfo->order_sn;
                        $priceLog->waybill = $orderInfo->waybill;
                        $priceLog->save();
                        if (!empty($pinfo['gzh_open_id'])) {
                            $data = [
                                'character_string12' => ['value' => $orderInfo->order_sn],
                                'amount6' => ['value' => $orderInfo->money],
                                'amount13' => ['value' => (string)$profit['profit']],
                            ];
                            $wechat = new WechatController();
                            $wechat->sendOfficialMessage($pinfo['gzh_open_id'], $templateId, $data);
                        }
                        break;
                    }
                }

                if (isset($profit['profit']) && $profit['profit'] > 0) {
                    //增加余额变动日志 待入账金额
                    $priceLog = [];
                    $priceLog = new MembersPriceLog();
                    $priceLog->user_id = $id;
                    $priceLog->start_user_id = $orderInfo->user_id;
                    $priceLog->money = $profit['profit'];
                    $priceLog->type = 2;
                    $priceLog->status = 0;
                    $priceLog->order_sn = $orderInfo->order_sn;
                    $priceLog->waybill = $orderInfo->waybill;
                    $priceLog->save();
                    if (!empty($pinfo['gzh_open_id'])) {
                        $data = [
                            'character_string12' => ['value' => $orderInfo->order_sn],
                            'amount6' => ['value' => $orderInfo->money],
                            'amount13' => ['value' => (string)$profit['profit']],
                        ];
                        $wechat = new WechatController();
                        $wechat->sendOfficialMessage($pinfo['gzh_open_id'], $templateId, $data);
                    }
                }
            }
        }
    }

    private function moreProfit($userId, $orderId, $platformId, $calWeight, $couponId)
    {

        $userInfo = Members::find($userId);
        $orderInfo = Orders::find($orderId);
        if (!empty($couponId) && $calWeight < 4 && $platformId == 3) {
            return true;
        }
        if ($platformId == 3) {
            $money = bcmul($calWeight, '0.1', 2);
        } else {
            $expressInfo = ExpressPlatform::where('express_code', $platformId)->where('type', $orderInfo->channel_tag)->first();
            $calPercent = $expressInfo->cal_more;
            $allMoney = bcadd($orderInfo->money, $orderInfo->overweight_money, 2);
            $money = bcmul($allMoney, strval((float)$calPercent / 100), 2);
        }
        //上级
        $path = Redis::hget($userId, 'path');
        if (!empty($path)) {
            $pathArr = explode(",", $path);
            $pathArr2 = [];
            $pathArr2 = array_reverse($pathArr);
            $v1Count = 0;
            $v2Count = 0;

            foreach ($pathArr2 as $id) {
                $profit = [];
                $profit['user_id'] = $id;
                $oldProfit = MembersProfit::where('user_id', $id)->where('order_id', $orderId)->where('type', 4)->first();
                if (empty($oldProfit)) {
                    $profit['type'] = 4; //续重分销
                } else {
                    $profit['type'] = 5; //订单退款
                }
                $profit['order_id'] = $orderId;
                $pinfo = Members::select(['pid', 'id', 'user_level', 'lose_all', 'user_count', 'v1_count', 'gzh_open_id'])->find($id);
                if (empty($pinfo)) continue;
                if ($userInfo->user_level == 0) {
                    //  v0-v1
                    if ($pinfo->user_level == 1 && $v1Count == 0 && $v2Count == 0) {
                        $v1Count = 1;
                        if ($oldProfit) {
                            $newProfit = bcsub((string)$oldProfit->profit, $money, 2);
                            $profit['profit'] = abs($newProfit);
                        } else {
                            $profit['profit'] = $money;
                        }

                        MembersProfit::create($profit);
                    } //v0-v2
                    elseif ($pinfo->user_level == 2 && $v1Count == 0 && $v2Count == 0) {
                        $v2Count = 1;
                        //使用优惠券

                        //不适用优惠券
                        if ($oldProfit) {
                            $newProfit = bcsub((string)$oldProfit->profit, $money, 2);
                            $profit['profit'] = abs($newProfit);
                        } else {
                            $profit['profit'] = $money;
                        }
                        MembersProfit::create($profit);

                    } //v0-v1-v2
                    elseif ($pinfo->user_level == 2 && $v1Count == 1 && $v2Count == 0) {
                        $v2Count = 1;
                        if ($oldProfit) {
                            $temp = bcmul($money, '0.35', 2);
                            $newProfit = bcsub((string)$oldProfit->profit, $temp, 2);
                            $profit['profit'] = abs($newProfit);
                        } else {
                            $temp = bcmul($money, '0.35', 2);
                            $profit['profit'] = $temp;
                        }
                        MembersProfit::create($profit);

                    } //v0-v2-v2
                    elseif ($pinfo->user_level == 2 && $v1Count == 0 && $v2Count == 1) {
                        if ($oldProfit) {
                            $temp = bcmul($money, '0.5', 2);
                            $newProfit = bcsub((string)$oldProfit->profit, $temp, 2);
                            $profit['profit'] = abs($newProfit);
                        } else {
                            $temp = bcmul($money, '0.5', 2);
                            $profit['profit'] = $temp;
                        }
                        MembersProfit::create($profit);
                        $priceLog = [];
                        $priceLog = new MembersPriceLog();
                        $priceLog->user_id = $id;
                        $priceLog->start_user_id = $orderInfo->user_id;
                        $priceLog->money = $profit['profit'];
                        $priceLog->type = 2;
                        $priceLog->status = 0;
                        $priceLog->order_sn = $orderInfo->order_sn;
                        $priceLog->waybill = $orderInfo->waybill;
                        $priceLog->save();
                        break;

                    } //v0-v1-v2-v2
                    elseif ($pinfo->user_level == 2 && $v1Count == 1 && $v2Count == 1) {
                        if ($oldProfit) {
                            $temp = bcmul($money, '0.175', 2);
                            $newProfit = bcsub((string)$oldProfit->profit, $temp, 2);
                            $profit['profit'] = abs($newProfit);
                        } else {
                            $temp = bcmul($money, '0.175', 2);
                            $profit['profit'] = $temp;
                        }

                        MembersProfit::create($profit);
                        $priceLog = [];
                        $priceLog = new MembersPriceLog();
                        $priceLog->user_id = $id;
                        $priceLog->start_user_id = $orderInfo->user_id;
                        $priceLog->money = $profit['profit'];
                        $priceLog->type = 2;
                        $priceLog->status = 0;
                        $priceLog->order_sn = $orderInfo->order_sn;
                        $priceLog->waybill = $orderInfo->waybill;
                        $priceLog->save();
                        break;

                    }
                } elseif ($userInfo->user_level == 1) {
                    //v1-v2
                    if ($pinfo->user_level == 2 && $v2Count == 0) {
                        $v2Count = 1;
                        if ($oldProfit) {
                            $newProfit = bcsub((string)$oldProfit->profit, $money, 2);
                            $profit['profit'] = abs($newProfit);
                        } else {
                            $profit['profit'] = $money;
                        }
                        MembersProfit::create($profit);
                    } //v1-v2-v2
                    elseif ($pinfo->user_level == 2 && $v2Count == 1) {
                        if ($oldProfit) {
                            $temp = bcmul($money, '0.5', 2);
                            $newProfit = bcsub((string)$oldProfit->profit, $temp, 2);
                            $profit['profit'] = abs($newProfit);
                        } else {
                            $temp = bcmul($money, '0.5', 2);
                            $profit['profit'] = $temp;
                        }
                        MembersProfit::create($profit);
                        $priceLog = [];
                        $priceLog = new MembersPriceLog();
                        $priceLog->user_id = $id;
                        $priceLog->start_user_id = $orderInfo->user_id;
                        $priceLog->money = $profit['profit'];
                        $priceLog->type = 2;
                        $priceLog->status = 0;
                        $priceLog->order_sn = $orderInfo->order_sn;
                        $priceLog->waybill = $orderInfo->waybill;
                        $priceLog->save();
                        break;

                    }
                } //v2
                elseif ($userInfo->user_level == 2) {
                    //v2-v2
                    if ($pinfo->user_level == 2 && $v2Count == 0) {
                        $v2Count = 1;
                        if ($oldProfit) {
                            $newProfit = bcsub((string)$oldProfit->profit, $money, 2);
                            $profit['profit'] = abs($newProfit);
                        } else {
                            $profit['profit'] = $money;
                        }
                        MembersProfit::create($profit);
                    } elseif ($pinfo->user_level == 2 && $v2Count == 1) {
                        //v2-v2-v2
                        $v2Count = 2;
                        if ($oldProfit) {
                            $temp = bcmul($money, '0.5', 2);
                            $newProfit = bcsub((string)$oldProfit->profit, $temp, 2);
                            $profit['profit'] = abs($newProfit);
                        } else {
                            $temp = bcmul($money, '0.5', 2);
                            $profit['profit'] = $temp;
                        }
                        MembersProfit::create($profit);
                    }

                }
                if (isset($profit['profit']) && $profit['profit'] != 0) {
                    //增加余额变动日志 待入账金额
                    $priceLog = [];
                    $priceLog = new MembersPriceLog();
                    $priceLog->user_id = $id;
                    $priceLog->start_user_id = $orderInfo->user_id;
                    $priceLog->money = $profit['profit'];
                    $priceLog->type = 2;
                    $priceLog->status = 0;
                    $priceLog->order_sn = $orderInfo->order_sn;
                    $priceLog->waybill = $orderInfo->waybill;
                    $priceLog->save();
                }
            }
        }
        return true;
    }


}
